﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Flower.SqlServer.Directory.DbGenerator.Generators
{
    internal class RemoveProcedure : IGenerator
    {
        private static readonly string RemoveProcedureTemplate;
        private static readonly string SpecificRemoveTemplate;

        static RemoveProcedure()
        {
            Assembly executingAssembly = Assembly.GetExecutingAssembly();

            using (var reader = new StreamReader(executingAssembly.GetManifestResourceStream(Program.ScriptsNamespace + ".RemoveProcedure.sql")))
            {
                RemoveProcedureTemplate = reader.ReadToEnd();
            }

            using (var reader = new StreamReader(executingAssembly.GetManifestResourceStream(Program.ScriptsNamespace + ".SpecificRemove.sql")))
            {
                SpecificRemoveTemplate = reader.ReadToEnd();
            }
        }

        public int Order
        {
            get { return 3; }
        }

        public void Generate(TextWriter writer, Settings settings)
        {
            Assembly executingAssembly = Assembly.GetExecutingAssembly();

            var specificRemovesBuilder = new StringBuilder();
            bool isFirst = true;

            foreach (EntriesDefinition.EntryDefinition entryDefinition in EntriesDefinition.Entries)
            {
                bool hasSpecificColumns =
                    entryDefinition.SpecificColumns != null &&
                    entryDefinition.SpecificColumns.Any(col => !col.Value.DontGenrateInsertUpdate);

                bool hasSpecificRemoves =
                    entryDefinition.SpecificRemoveScriptResource != null;

                if (!(hasSpecificColumns || hasSpecificRemoves))
                {
                    isFirst = false;
                    continue;
                }

                specificRemovesBuilder.AppendFormat
                (
                    "\t{0}IF @Type = {1}\n", 
                    (!isFirst) ? "ELSE " : string.Empty,
                    entryDefinition.DirectoryEntryType
                );
                specificRemovesBuilder.AppendLine("\tBEGIN");

                if (hasSpecificColumns)
                {
                    specificRemovesBuilder.AppendLine
                    (
                        Helper.Tabify
                        (
                            SpecificRemoveTemplate.Replace("/*--EntryName--*/", entryDefinition.Name),
                            "\t\t"
                        )
                    );
                }

                if (hasSpecificRemoves)
                {
                    using (var reader = new StreamReader(executingAssembly.GetManifestResourceStream(string.Concat(Program.ScriptsNamespace, ".", entryDefinition.SpecificRemoveScriptResource, ".sql"))))
                    {
                        specificRemovesBuilder.AppendLine
                        (
                            Helper.Tabify
                            (
                                reader.ReadToEnd(),
                                "\t\t"
                            )
                        );
                    }
                }

                specificRemovesBuilder.AppendLine("\tEND");

                isFirst = false;
            }

            writer.WriteLine
            (
                RemoveProcedureTemplate
                    .Replace("/*--SpecificDeletes--*/", specificRemovesBuilder.ToString())
            );
            writer.WriteLine();
        }
    }
}
